package com.cy.demosharding.config;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.time.LocalDateTime;
import java.util.Collection;

/**
 * @author hulei
 * @version 1.0
 * @date 2022-01-07 10:30
 * @target
 */
public class MonthShardingAlgorithm implements PreciseShardingAlgorithm<LocalDateTime>, RangeShardingAlgorithm<LocalDateTime> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<LocalDateTime> preciseShardingValue) {
        LocalDateTime dateTime = preciseShardingValue.getValue();
        int month = dateTime.getMonthValue();
        for (String tableName : collection) {
            if (tableName.endsWith(String.valueOf(month))) {
                return tableName;
            }
        }
        throw new UnsupportedOperationException(
                String.format("MonthShardingAlgorithm not support,logicTableName:%s,month:%s,tableList:%s ",
                        preciseShardingValue.getLogicTableName(),
                        month,
                        collection));
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<LocalDateTime> rangeShardingValue) {
        return collection;
    }
}
